import React, { Component } from "react";
export default class App extends Component {
  state = { username: "carlos", age: 25 ,hasError:'',flag:true};
  static getDerivedStateFromError(error){
    console.log('error',error);
    return {hasError:error}
  }
  componentDidCatch(){
    console.log('页面出现了错误');
  }
  render() {
    const {hasError,flag}=this.state
    const renderData=()=>{
      if(!flag){
        return <h1>正常情况1</h1>
      }else{
        return <h1>正常情况2</h1>
      }
    }
    console.log('hasError',hasError);
    if(hasError){
      console.log('yes');
    }else{
      console.log('no');
    }
    return (
      <div style={{ padding: "5px", backgroundColor: "gray" }}>
        fa
        {/* 两种写法一样的 */}
        {/* <Son>test内容</Son> */}
        {/* <Son children="test内容"/> */}
        {/* 使用插槽，孙子可以用儿子组件的数据 */}
        {!hasError?<Son render={(data) => <Grandson data={data}></Grandson>}></Son>:<h4>网络出现了问题</h4>}
        <br></br>{renderData()}
      </div>
    );
  }
}
class Son extends Component {
  state = { username: "carlosSon",arr:[{id:0,name:'test1'},{id:1,name:'test2'}] };
  // state = { username: "carlosSon",arr:'test' };
  render() {
    const { username,arr } = this.state;
    return (
      <div className="son" style={{ padding: "5px", backgroundColor: "skyblue" }}>
        son内容：{this.props.render(username)}<br/>
        arr:{arr.map(obj=>{
          return <span key={obj.id}>{obj.name}</span>
        })}
      </div>
    );
  }
}
class Grandson extends Component {
  state = { username: "carlosGrand" };
  render() {
    const { username } = this.state;
    console.log(this.props);
    return (
      <div className="grandson" style={{ padding: "5px", backgroundColor: "yellow" }}>
        grandson：{this.props.data}
      </div>
    );
  }
}
